package util;

import com.alibaba.fastjson.JSON;

import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

/**
 * 封装set结果集
 *
 * @param <T>
 */
public class GetResultSet <T>{
    public T get(Class<T> clazz, ResultSet set) throws SQLException {
        Field[] fields = clazz.getDeclaredFields();
        StringBuilder str = new StringBuilder("{");
        for (int i = 0; i < fields.length; i++) {
            fields[i].setAccessible(true);
            if(fields[i].getType() == String.class){
                str.append("\"").append(fields[i].getName()).append("\"");
                str.append(":\"").append(set.getString(i + 1)).append("\",");
            }
            if(fields[i].getType() == Integer.class || fields[i].getType() == int.class){
                str.append("\"").append(fields[i].getName()).append("\"");
                str.append(":").append(set.getInt(i + 1)).append(",");
            }
            if(fields[i].getType() == Date.class){
                str.append("\"").append(fields[i].getName()).append("\"");
                str.append(":\"").append(set.getDate(i + 1)).append("\",");
            }
        }
        str.append("}");
        return JSON.parseObject(str.toString(), clazz);
    }
}
